package com.wyp168.socket.tcp.upload;

import com.wyp168.socket.utils.StreamUtils;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

@SuppressWarnings({"all"})
public class Client {
    public static void main(String[] args) throws Exception{
        //客户端连接服务端，得到Socket对象
        Socket socket = new Socket(InetAddress.getLocalHost(), 9002);
        //读取磁盘中的图片资源
        String sourcePath = "/Users/wangyuanpeng/com/wyp168.jpg";
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourcePath));

        //bytes 就是 filePath 对应的字节数组
        byte[] bytes = StreamUtils.streamToByteArray(bis);

        //通过socket 获取到输出流， 将bytes 内容 发送给服务端
        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
        bos.write(bytes);   //将文件字节数组写入到数据通道
        bos.flush();
        bis.close();
        socket.shutdownOutput();    //设置文件结束符

        InputStream inputStream = socket.getInputStream();
        byte[] buf = new byte[1024];
        int readLen;
        while ((readLen = inputStream.read(buf)) != -1) {
            System.out.println(new String(buf, 0, readLen));
        }



        //关闭相关流
        inputStream.close();
        bos.close();
        socket.close();

    }
}
